<template>
  <div id="userAvatar-container">
    <img :src="img" id="image" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="confirm">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user.js'

export default {
  name: 'userAvatar',
  props: {
    img: {
      type: String,
      required: true
    }
  },
  data () {
    return {}
  },
  created () {},
  mounted () {
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  },
  methods: {
    confirm () {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        loadingType: 'spinner',
        message: '裁剪中....'
      })
      // 1、服务器裁剪
      // console.log(this.cropper.getData())
      // 2、客户端裁剪
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // console.log(blob)
        const forms = new FormData()
        forms.append('photo', blob)
        try {
          const res = await updateUserPhoto(forms)
          // console.log(res)
          this.$toast.success('更新成功')
          // 关闭弹层，更新视图
          this.$emit('close')
          this.$emit('update-avatar', res.photo)
        } catch (err) {
          this.$toast.fail('更新失败')
        }
      })
    }
  }
}
</script>

<style lang='less' scoped>
#userAvatar-container {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
